package com.tom.demo.common.utils;

import org.apache.poi.sl.usermodel.TextParagraph;
import org.apache.poi.sl.usermodel.VerticalAlignment;
import org.apache.poi.xslf.usermodel.*;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.springframework.util.StringUtils;

import java.awt.*;
import java.util.List;

public class HtmlToPptUtil {

    public static void htmlElementHandle(XSLFTextShape xslfTextShape, Elements allElements){
        for (Element element : allElements) {
            //body不做处理
            if("body".equals(element.tagName())){
                continue;
            }
            if("p".equals(element.tagName())){
                //创建一个段落对象
                XSLFTextParagraph xslfTextParagraph = xslfTextShape.addNewTextParagraph();
                XSLFTextRun xslfTextRun = xslfTextParagraph.addNewTextRun();
                //获取上面的样式信息
                List<Node> nodes = element.childNodes();
                for (Node node : nodes) {
                    String style = node.attr("style");
                    System.out.println(style);
                    setSelfStyle(xslfTextRun,style);
                }
                xslfTextParagraph.setLeftMargin(0.0);
                htmlLabelHandler(xslfTextShape,xslfTextParagraph,element.childNodes(),xslfTextRun,element);
                xslfTextParagraph.removeTextRun(xslfTextRun);

            }
            if("ul".equals(element.tagName())){
                //创建一个段落对象
                XSLFTextParagraph xslfTextParagraph = xslfTextShape.addNewTextParagraph();
                XSLFTextRun xslfTextRun = xslfTextParagraph.addNewTextRun();
                //获取上面的样式信息
                String style = element.childNode(0).attr("style");

                setSelfStyle(xslfTextRun,style);
                //body不做处理
                xslfTextParagraph.setLeftMargin(0.0);
                htmlLabelHandler(xslfTextShape,xslfTextParagraph,element.childNodes(),xslfTextRun,element);
                xslfTextParagraph.removeTextRun(xslfTextRun);
            }

        }
    }

    public static void setSelfStyle(XSLFTextRun textRun, String style) {
        // 字体大小
        double fontSize = getFontSize(style, textRun.getFontSize());
        textRun.setFontSize(fontSize);
        // 字体颜色
        Color fontColor = getColor(style, "color");
        if (null != fontColor) {
            textRun.setFontColor(fontColor);
        }
        // 粗体
        if (style.contains("font-weight")) {
            textRun.setBold(true);
        }if (style.contains("text-decoration") || style.contains("text-decoration-line")) {
            // 下划线
            if (style.contains("underline")) {
                textRun.setUnderlined(true);
            }
            // 删除线
            if (style.contains("line-through")) {
                textRun.setStrikethrough(true);
            }
        }
            // 斜体
        if (style.contains("font-style: italic") || style.contains("font-style:italic")) {
            textRun.setItalic(true);
        }
        // 设置字体
        textRun.setFontFamily("Microsoft YaHei");
        String fontFamily = getFontFamily(style, null);
        textRun.setFontFamily(fontFamily);
    }


    /**
     * 获取字体大小
     */
    public static double getFontSize(String style, double defaultSize) {
        double thisFontSize = 14;
        if (style.contains("font-size")) {
            String sizeStr = style.replaceAll(".*font-size:\\s*(\\d+(\\.\\d+)?)px\\s*.*", "$1");
            thisFontSize = Double.parseDouble(sizeStr);
        } else {
            thisFontSize = defaultSize;
        }
        return thisFontSize;
    }

    /**
     * 获取颜色
     */
    public static Color getColor(String style, String property) {
        String colorValue = getStyleColorValue(style, property);
        if (!StringUtils.hasText(colorValue)) {
            return null;
        }
        if (!colorValue.contains("rgb") && !colorValue.contains("#")) {
            return null;
        }
        if (colorValue.contains("rgb")) {
            String colorStr = colorValue.replaceAll("[^0-9,]", "");
            String[] rgb = colorStr.split(",");
            return new Color(Integer.parseInt(rgb[0]), Integer.parseInt(rgb[1]), Integer.parseInt(rgb[2]));
        }
        return Color.decode(colorValue);
    }
    /**
     * 获取style中颜色的值
     */
    public static String getStyleColorValue(String style, String property) {
        String regex = property + ":\\s*([^;]+);?";
        String value = "";

        // 使用正则表达式提取 CSS 属性值
        if (style.matches(".*" + regex + ".*")) {
            value = style.replaceAll(".*" + regex + ".*", "$1").trim();
        }
        return value;
    }

    public static Color getColorByRgb(String style) {
        if (style.contains("rgba")) {
            String colorStr = style.replaceAll("[^0-9,]", "");
            String[] rgb = colorStr.split(",");
            return new Color(Integer.parseInt(rgb[0]), Integer.parseInt(rgb[1]), Integer.parseInt(rgb[2]), Integer.parseInt(rgb[3]));
        } else if (style.contains("rgb")) {
            String colorStr = style.replaceAll("[^0-9,]", "");
            String[] rgb = colorStr.split(",");
            return new Color(Integer.parseInt(rgb[0]), Integer.parseInt(rgb[1]), Integer.parseInt(rgb[2]));
        }
        return Color.decode(style);
    }
    /**
     * 获取字体
     */
    public static String getFontFamily(String style, String defaultFontFamily) {
        String thisFontFamily = "楷体";
        if(style.contains("font-family")) {
            thisFontFamily = style.replaceAll("(.*font-family:\\s*)|(;.*)", "").trim();
        }
        else if(StringUtils.hasText(defaultFontFamily)) {
            thisFontFamily = defaultFontFamily;
        }
        return thisFontFamily;
    }

    /**
     * html标签处理
     */
    public static void htmlLabelHandler(XSLFTextShape textShape, XSLFTextParagraph paragraph, List<Node> nodeList, XSLFTextRun parentTextRun,
                                        Element parentElement) {
        for (Node node : nodeList) {
            String style = node.attr("style");
            if (node instanceof Element) {
                // li
                if ("li".equals(((Element) node).tag().getName())) {
                    XSLFTextParagraph liTextRuns = textShape.addNewTextParagraph();
                    liTextRuns.setBullet(true);
                    XSLFTextRun textRun = liTextRuns.addNewTextRun();
                    // textRun.setText(" ");
                    setStyleByParent(textRun, parentTextRun);
                    setSelfStyle(textRun, style);
                    if (node.childNodeSize() > 0) {
                        htmlLabelHandler(textShape, liTextRuns, node.childNodes(), textRun, (Element) node);
//                        liTextRuns.removeTextRun(textRun);
                    } else {
                        textRun.setText(((Element) node).text());
                    }
                } else {
                    // 换行
                    if ("br".equals(((Element) node).tag().getName())) {
                        paragraph.addLineBreak();
                        continue;
                    }
                    XSLFTextRun textRun = paragraph.addNewTextRun();
                    setStyleByParent(textRun, parentTextRun);
                    setSelfStyle(textRun, style);
                    // 加粗
                    if ("strong".equals(((Element) node).tag().getName()) || "b".equals(((Element) node).tag().getName())) {
                        textRun.setBold(true);
                    }
                    // 斜体
                    if ("em".equals(((Element) node).tag().getName())) {
                        textRun.setItalic(true);
                    }
                    // 删除线
                    if ("s".equals(((Element) node).tag().getName())) {
                        textRun.setStrikethrough(true);
                    }
                    // 下划线
                    if ("u".equals(((Element) node).tag().getName())) {
                        textRun.setUnderlined(true);
                    }
                    // 处理下级标签或者文字
                    if (node.childNodeSize() > 0) {
                        htmlLabelHandler(textShape, paragraph, node.childNodes(), textRun, (Element) node);
                        paragraph.removeTextRun(textRun);
                    } else {
                        textRun.setText(((Element) node).text());
                    }
                }

            } else if (node instanceof TextNode) {
                XSLFTextRun textRun = paragraph.addNewTextRun();
                textRun.setText(((TextNode) node).text());
                setStyleByParent(textRun, parentTextRun);
                setSelfStyle(textRun, style);
            }
        }
    }

    public static void setStyleByParent(XSLFTextRun textRun, XSLFTextRun parentTextRun) {
        textRun.setFontColor(parentTextRun.getFontColor());
        textRun.setFontSize(parentTextRun.getFontSize());
        textRun.setItalic(parentTextRun.isItalic());
        textRun.setUnderlined(parentTextRun.isUnderlined());
        textRun.setStrikethrough(parentTextRun.isStrikethrough());
        textRun.setBold(parentTextRun.isBold());
    }

//    public void centerTextInTable(XSLFTable table) {
//        // 遍历表格的所有行
//        for (XSLFTableRow row : table.getRows()) {
//            // 遍历行内的所有单元格
//            for (XSLFTableCell cell : row.getCells()) {
//                // 设置单元格的垂直对齐方式为中间
//                cell.setVerticalAlignment(VerticalAlignment.MIDDLE);
//                // 设置单元格对齐
//                XSLFTextParagraph paragraph = cell.getTextParagraphs().get(0);
//                paragraph.setTextAlign(TextAlign.CENTER);
//                // 遍历单元格内的所有段落
//                for (XSLFTextParagraph paragraph : cell.getTextFrame().getParagraphs()) {
//                    // 设置段落的水平对齐方式为中心
//                    paragraph.setAlignment(TextParagraph.TextAlign.CENTER);
//                }
//            }
//        }
//    }
}
